<?php

class User extends NetModel
{
    public $account;
    public $username;
    public $password;
    public $confirmpass;
    public $new_password;
    public $mobile;
    public $name;
    public $email;
    public $role;
    public $group;
    public $status;
    public $created;
    public $register_method;
    public $user_id;
    public $old_password;
    public $identity;
    public $verifyCode;
    public $recommend_user;
    public $source;
    public $token;
    public $register_from;

    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }
    public function attributeNames(){
        return array(
                'account',
                'mobile',
                'password',
                'recommend_user',
                'register_method',
                'register_from'
            );
    }
    public function attributeLabels()
    {
        return array(
            'username'       => '用户名',
            'name'           => '姓名',
            'password'       => '密码',
            'confirmpass'    => '确认密码',
            'mobile'         => '手机号',
            'email'          => '电子邮件',
            'old_password'   => '旧密码',
            'role'           => '用户角色',
            'created'        => '注册时间',
            'identity'       => '身份证号',
            'recommend_user' => '推荐注册用户'
        );
    }

    public function rules()
    {
        return array(
            array('mobile','required','on'=>'register','message'=>'请输入手机号码'),
            array('mobile','match','pattern'=>'/^1[3|4|5|7|8][0-9]{9}$/','message'=>'请输入正确的手机号码','skipOnError'=>true),
            array('mobile','checkMobile','on'=>'register','skipOnError'=>true),
            array('verifyCode','required','on'=>'register','message'=>'请输入正确的验证码'),
            array('verifyCode','checkVerifyCode','on'=>'register','skipOnError'=>true),
            array('password,confirmpass', 'required','on'=>array('modpass')),
            array('old_password', 'required','on'=>'modpass','message' => '请输入正确的旧密码'),
            array('password','length','is' => 32,'message'=>'密码长度不对'),
            array('password','checkPassword','skipOnError'=>true),
            array('confirmpass', 'compare', 'compareAttribute'=>'password',
                'message' => '确认密码跟密码必须一致','on'=>array('modpass')),
            array('email','email','on'=>array('modifan','boundemail')),
            array('register_method','in','range'=>array(6,7),'allowEmpty' => false,'message'=>'illegal register param'),//6:ios 7:android
            array('username,source,created,status,name,user_id,identity,recommend_user,register_method,password,mobile','safe'),
        );
    }
    /**
     * 校验手机号是否已经注册
     */
    public function checkMobile()
    {
        if(self::mobileRegistered($this->mobile))
            $this->addError('mobile','该手机号已经注册，请直接登陆');
    }
    /**
     * 校验手机验证码
     */
    public function checkVerifyCode()
    {
        if(Helper::getCode($this->mobile) != $this->verifyCode)
            $this->addError('verifyCode','验证码不正确');
    }
    /**
     * 校验密码是否过于简单
     */
    public function checkPassword()
    {
        if(Helper::checkIsSimplePass($this->password))
            $this->addError('password','密码过于简单，请使用安全系数更高的密码');
    }

    /**
     * 获取用户得投资记录
     * @param $user_id
     * @param $page
     * @param $pay_status 0:投资中 1：已结算
     * @return array
     */
    public function getTranList($user_id,$page=1,$limit=15,$pay_status = 0,$order = 1)
    {
        $return = array('success'=>0);
        $cache  = Yii::app()->cache_new;
        if(!$cache->hget('userTransListTag',$user_id))
        {
            $remote = HttpLib::get('transaction/init/user/transactions.json',array(
                'user_id' => $user_id,
            ));
            if(!$remote->success)
            {
                $data['msg'] = $remote->errorMsg;
                $this->setResult($data);
            }
        }
        $k     = 'userTransList.'.$user_id;
        if(!$order)
            $k = 'userLastTransList.'.$user_id;
        if($pay_status==1)
            $k = 'userFinishedTransList.'.$user_id;
        $pipe  = $cache->pipeline();
        $pipe->llen($k);
        $pipe->lrange($k,($page-1)*$limit,$page*$limit-1);
        list($count,$list) = $pipe->exec();
        $return['pageNum']    = (int)(($count+$limit-1)/$limit);
        $return['success']    = 1;
        $return['totalCount'] = $count;
        $return['investList'] = array();
        $status = array(
            0 => '投资中',
            1 => '已结算',
            2 => '提前还本付息',
        );
        foreach($list as $value)
        {
            $value = json_decode($value);
            if($value->typeCode==9)
                continue;
            $return['investList'][] = array(
                'transactionId' => $value->transactionId,
                "projectName"   => $value->projectName,
                "projectId"     => $value->projectId,
                "amount"        => $value->investAmount,
                "rate"          => $value->annualizedRate,
                'endTime'       => date('Y-m-d',$value->endTime/1000),
                'status'        => $status[$value->payStatus],
                'gmtCreated'    => date('Y.m.d',$value->gmtCreated/1000),
                'transferCode'  => $value->transferCode,
                'days'          => $value->payStatus==0?intval(($value->endTime/1000-strtotime(date('Y-m-d')))/3600/24):0,
            );
        }
        $capital = self::model()->getCapital($user_id);
        $return['receivableInterest'] = $capital['receivableInterest'];
        $return['receivedInterest']   = $capital['receivedInterest'];
        $return['usedRewardTotal']    = $capital['usedRewardTotal'];
        $e                            = User::model()->getEwalletInfo($user_id);
        $return['eTotal']             = $e['eTotal'];//e钱包总额
        $return['tip']                = '会生钱的钱包';
        return $return;
    }

    /**
     * 取现前判断
     */
    public function getWithDraw($user_id)
    {
        $data = array('success' => 0);
        $user = self::model();
        $info = $user->findById($user_id);
        if(!$info->resetPayPass)
        {
            $data['msg']     = '请先设置交易密码';
            $data['success'] = -7;
        }
        elseif(!$info->authenticated)
        {
            $data['msg']     = '请先实名认证';//未实名认证 未绑卡
            $data['success'] = -4;
        }
        elseif($user->inWithdrawBlackList($user_id))
        {
            $data['msg']     = '您现在无法进行提现，请联系客服了解情况';
            $data['success'] = -3;
        }
        elseif(!$info->realAuthenticated)
        {
            $data['name']     = $info->name;
            $data['identity'] = $info->identity;
            $card             = $this->getBankCard($user_id);
            $cardinfo         = $card[0];
            if($cardinfo === array())
                $data['success'] = -8;
            elseif(!$cardinfo['supportLL'])
            {
                $data['success'] = -9;
                $data['msg']     = Yii::app()->params['bankCardNotSupport'];
            }
            else
            {
                $data['success'] = -10;
                $data['list'] = array(
                    'bank_id'        => $cardinfo['bankId'],
                    'fullCardNumber' => $cardinfo['fullCardNumber'],
                    'bankName'       => $cardinfo['bankName'],
                );
            }
        }
        elseif($info->realAuthenticated) //真正实名认证
        {
            $card                 = $this->getBankCard($user_id);
            $cardinfo             = $card[0];
            if($cardinfo === array()) //未绑卡
            {
                $data['success']      = -11;
                $data['starName']     = $info->starName;
                $data['name']         = $info->name;
                $data['identity']     = $info->identity;
                $data['starIdentity'] = $info->starIdentity;
            }
            else
            {
                if(!$this->checkWithDrawToday($user_id))
                {
                    $data['msg']                    = '亲，今天您已经提过一次了';
                    $data['success']                = -2;
                    $data['list']                   = array();
                    $data['list']['bankCard']       = $card;
                    $capital                        = $user->getCapital($user_id);
                    $data['list']['capitalBalance'] = $capital['capitalAccountBalance'];
                    $data['list']['tip']            = Yii::app()->params['withdrawTimeTip'];
                }
                else
                {
                    if($card[0]['needUpdate'])
                    {
                        $data['success']          = -6;
                        $data['msg']              = '需要完善信息';
                        $card_number  = $card[0]['fullCardNumber'];
                        $data['list'] = array(
                            'card_id'         => $card[0]['card_id'],
                            'bank_id'         => $card[0]['bankId'],
                            'bankName'        => $card[0]['bankName'],
                            'starBankAccount' => mb_substr($card_number, 0,4).' **** **** '.mb_substr($card_number,-4),
                            'tip'             => '请填写您名下的银行卡，并确保与草根实名认证一致',
                            'starIdentity'    => $info->starIdentity,
                            'starName'        => $info->starName,
                        );
                    }
                    else
                    {
                        $data['list']                   = array();
                        $data['list']['bankCard']       = $card;
                        $capital                        = $user->getCapital($user_id);
                        $data['success']                = 1;
                        $data['msg']                    = '请求成功';
                        $data['list']['capitalBalance'] = $capital['capitalAccountBalance'];
                        $data['list']['tip']            = Yii::app()->params['withdrawTimeTip'];
                    }
                }
            }
        }
        if(in_array($data['success'], array(-4,-8,-9,-10,-11,-12,-13)))
            $data['bindFee'] = Yii::app()->params['bindCardFee'];
        return $data;
    }
    /**
     * 判断是否可以提现
     */
    public function checkWithDrawToday($user_id)
    {
        if(Yii::app()->cache2->hget('WithdrawTimes',$user_id))//已经提现
            return false;
        return true;
    }
    /**
     * 获取用户银行卡信息
     */
    public function getBankCard($user_id)
    {
        $cardinfo = array();
        $cache = Yii::app()->cache2->hget($user_id.'.Capital','bankCard');
        if($cache && json_decode($cache)->result == 'nobank') //未绑定银行卡
        {
            $cardinfo[] = array();//未设置银行卡
            return $cardinfo;
        }
        elseif($cache)
            $card = json_decode($cache);
        else
        {
            $remote = HttpLib::get($this->javaApi['bankcard_list'],array(
                'user_id'=>$user_id,
                'page'=>1
            ));
            if($remote->success && $remote->result)
                $card = $remote->result;
            elseif(!$remote->success && $remote->code == 20106)
            {
                $cardinfo[] = array();//未设置银行卡
                return $cardinfo;
            }
        }
        $supportLL  = 0;//银行支持连连
        $needUpdate = 0;//需要完善信息
        $banks = Yii::app()->params['mobileBanks'];
        $needBranch = 0;
        $needBranchBankIds = Yii::app()->params['spNeedBranchBankIds'];
        $withdrawChannal   = Yii::app()->cache2->get('withdrawChannal');
        if($withdrawChannal)
        {
            $withdrawChannal = json_decode($withdrawChannal);
            if($withdrawChannal->channel == 'll')
                $needBranchBankIds = Yii::app()->params['llNeedBranchBankIds'];
        }
        if(in_array($card->bankId,$needBranchBankIds))
        {
            $needBranch = 1;
            if(!$card->bankProvince || !$card->bankCity || !$card->subBranchName)
                $needUpdate = 1;
        }
        foreach($banks as $bank)
        {
            if($bank['code']==$card->bankId)
                $supportLL = 1;
        }
        $llMark  = ($card->status==0 && $supportLL )?1:0;//连连标识
        if(strpos($card->cardNumber, '*') === false)
        {
            $card->fullCardNumber = $card->cardNumber;
            $card->cardNumber     = str_repeat("*", strlen($card->cardNumber)-4).substr($card->cardNumber,-4,4);
        }
        $cardinfo[] = array(
            'card_id'        => $card->id,
            'cardNumber'     => $card->cardNumber,
            'starCardNumber' => mb_substr($card->fullCardNumber, 0,4).' **** **** '.mb_substr($card->fullCardNumber,-4),
            'fullCardNumber' => $card->fullCardNumber,
            'last4number'    => substr($card->fullCardNumber,-4,4),//str_replace('*', '', $card->cardNumber),
            'cardLast'       => substr($card->cardNumber,-4,4),
            'cardHolder'     => $card->cardHolder,
            'bankId'         => $card->bankId,
            'bankProvince'   => $card->bankProvince?$card->bankProvince:'',
            'bankCity'       => $card->bankCity?$card->bankCity:'',
            'branchName'     => $card->subBranchName?$card->subBranchName:'',
            'bankName'       => Yii::app()->params['bankcards'][$card->bankId],
            'supportLL'      => $supportLL,
            'llMark'         => $llMark,//连连标识
            'needUpdate'     => $needUpdate,
            'needRebind'     => $this->needReBind($card->bankId),
            'payMethod'      => 3,//优先支付通道 3连连 5联动优势
            'payLimit'       => Helper::getBankPayLimit($card->bankId,3),
            'protocolNo'     => $card->protocolNo?$card->protocolNo:'',
        );
        return $cardinfo;
    }
    /**
     * 获取银行卡是否需要重新绑定
     * @param  [type] $bank_id [description]
     * @return [type]          [description]
     *  0 --不需要重新绑定
     *  1 --需要重新绑定
     *  -1 -- 支付通道关闭
     */
    private function needReBind($bank_id)
    {
        $needRebind = 0;
        $channel = Helper::chooseChannel($bank_id);
        switch($channel)
        {
            case 'LL':
                $needRebind = 0;
                break;
            case 'UMP':
                $needRebind = 0;
                break;
            case 'NOT_SUPPORT':
                $needRebind = 1;
                break;
            case 0:
                $needRebind = -1;
                break;
        }
        return $needRebind;
    }

    private function fn($number)
    {
        return sprintf("%.2f",$number);
    }
    private function diffDay($start,$end)
    {
        return round((strtotime($start)-strtotime($end))/3600/24);
    }
    /**
     * 检验手机号是否已经注册
     * true:已注册 false:未注册
     */
    public static function mobileRegistered($mobile)
    {
        return Yii::app()->cache_php->hexists('cgtz_registered_mobiles',$mobile)?true:false;
    }

    /**
     * @param $pk
     * @return mixed|null
     */
    public function findByPK($pk)
    {
        return $this->findById($pk);
    }
    /**
     * 获取用户信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function findById($id)
    {
        $cache = Yii::app()->cache2->hget($id.'.Capital','UserInfo');
        if($cache)
        {
            $info = json_decode($cache);
        }
        else
        {
            $remote = HttpLib::post('login/getUserCenterInfo.json',array('user_id'=>$id),'back_host2');
            if($remote->success && $remote->result)
            {
                $info = $remote->result;
            }
            else
            {
                echo json_encode(array(
                    'success' => 0,
                    'msg'     => $remote->errorMsg,
                ));
                Yii::app()->end();
            }
        }
        $data = new stdClass();
        $data->email               = $info->email;
        $data->from                = $info->from;
        $data->identity            = $info->identity;
        $data->starIdentity        = $info->identity?Helper::mb_substr_replace($info->identity,'*********',6,9):'';
        $data->identityStr         = $info->identityStr;
        $data->mobile              = $info->mobile;
        $data->mobileStr           = $info->mobileStr;
        $data->name                = $info->name;
        $data->starName            = $info->name?Helper::mb_substr_replace($info->name,'*',1,1):'';
        $data->resetPayPass        = $info->resetPayPass?0:1;
        $data->shortUrl            = $info->shortUrl;
        $data->userExtend          = $info->userExtend;
        $data->userId              = $info->userId;
        $data->identityVerify      = $info->identityVerify?1:0;
        $data->invest              = $info->invest?true:false;
        $data->authenticated       = $info->name && $info->identity;
        $data->realAuthenticated   = 0;
        if($data->authenticated && $info->identityVerify)
            $data->realAuthenticated   = 1;
        return $data;
    }
    /**
     * 用户推荐列表调用和判断用户是否投资调用
     */
    public function getUserInfo($id)
    {
        $cache = Yii::app()->cache2->hget($id.'.Capital','UserInfo');
        if($cache)
            $info = json_decode($cache);
        else
            return null;
        $data            = new stdClass();
        $data->mobile    = $info->mobile;
        $data->mobileStr = $info->mobileStr;
        $data->invest = $info->invest?true:false;
        return $data;
    }

    public function beforeSave()
    {
        $this->status      = 1;
        $this->created     = time();
        $this->username    = '';
        $this->account     = $this->mobile;
        $this->password    = $this->password;
        return true;
    }
    /**
     * 保存管理员资料
     * @return bool
     */
    public function save()
    {
        $this->beforeSave();
        $params = array_merge($this->attributes,Yii::app()->params['globalParams']);
        $result = HttpLib::post(Yii::app()->params['scripts']['user_register'],$params);

        if($result && $result->success )
        {
            if(MOBILEOS == 'ios')
            {
                Helper::pushIFA($this->mobile,'register');
            }
            try{
                $pip = Yii::app()->cache_php->multi();
                $pip->incr("TotalRegisterUser");
                $pip->hset("cgtz_registered_mobiles",$this->mobile,1);
                if($this->register_method == 6)
                    $pip->incrby("TotalIosRegisters",1);
                elseif($this->register_method == 7)
                    $pip->incrby("TotalAndroidRegisters",1);
                $pip->exec();
            }catch (Exception $ex)
            {
                Yii::log('user after save redis error',CLogger::LEVEL_ERROR);
                $pip->discard();
            }
            return true;
        }
        return false;
    }
    /**
     * 获取可用的奖励
     */
    public function getUsableRewards($user_id)
    {
        $remote = HttpLib::post(Yii::app()->params['scripts']['get_usable_reward'],array('user_id'=>$user_id));
        $data = array('success'=>0,'msg'=>$remote->errorMsg);
        if($remote->success)
        {
            $data['success'] = 1;
            $data['msg']     = '请求成功';
            $data['result']  = $remote->result;
            foreach($remote->result as $key=>$r)
            {
                if($r->coupon_type==0)
                {
                    $remote->result[$key]->amount = number_format(intval($r->amount*100)/100,2,'.','');
                }
            }
            $capital = User::model()->getCapital($user_id);
            $data['capitalAccountBalance'] = $capital['capitalAccountBalance'];
            $config = Yii::app()->cache_php->hget('MOBILE_APP_CONFIG','reward');
            $config = json_decode($config);
            $data['rewardInstruction'] = $config->instruction;
            if(MRedis::getUserInvestedNum($user_id) < 2)
            {
                $data['rewardTitle']   = $config->title;
                $data['rewardContent'] = $config->content;
            }

        }
        return $data;
    }

    /**
     * 用户是否投资过
     */
    public function invested($userId)
    {
        $info = $this->getUserInfo($userId);
        if($info && $info->invest)
            return true;
        return false;
    }

    /**
     * 判断当前用户是否可以购买当前的项目(判断是否可以购买新人专享项目)
     * @param  [type]  $user_id   [description]
     * @param  [type]  $projectId [description]
     * @return boolean            [description]
     */
    public function  isAbleToBuy($user_id,$projectId)
    {
        if(!$this->invested($user_id))
            return true;
        if(Project::isOnlyForNew($projectId))
            return false;
        return true;
    }
    /**
     *
     */
    public function getMobileCode()
    {
        return Yii::app()->cache2->get('verifyCode.'.$this->mobile);
    }
    /**
     * 第三方实名认证
     */
    public function IsRealAuthenticated($user_id)
    {
        $remote  = HttpLib::get(Yii::app()->params['scripts']['user_real_name_validate'],array('user_id'=>$user_id));
        if($remote->success)
            return true;
        return false;
    }
    /**
     * 获取用户账户资金信息
     * @return ArrayObject
     */
    public function getCapital($user_id)
    {
        $return = array(
            'capitalAccountBalance' => 0,
            'recommendedAmount'     => 0,
            'recommendedCount'      => 0,
            'withdrawFrozen'        => 0,
            'rechargeTotal'         => 0,
            'totalRewardCash'       => 0,
            'investingAmount'       => 0,
            'investingCount'        => 0,
            'receivedInterest'      => 0,
            'receivableInterest'    => 0,
            'receivablePrincipal'   => 0,
            'totalRechargeCount'    => 0,
            'totalInvestAmount'     => 0,
            'finishedInvestTotal'   => 0,
            'rewardAccountBalance'  => 0,
            'demandBalance'         => 0,
            'demandPayableInterest' => 0,
            'demandHistory'         => 0,
            'demandIncome'          => 0,
            'redeemDemandBalance'   => 0,//待赎回的e本金
            'coupon' => array(
                'annualTotalCount'   => 0,
                'annualUsableCount'  => 0,
                'couponAmount'       => 0,
                'couponCount'        => 0,
                'couponUsableAmount' => 0,
                'couponUsableCount'  => 0,
                'usedCouponAmount'   => 0,
                'usedRewardAmount'   => 0,
            ),
        );
        $balance  = $this->getBalance($user_id);
        $return['rewardAccountBalance']  = Helper::formatNumber($balance['RewardAccountBalance'],2);//可用红包金额
        $return['capitalAccountBalance'] = Helper::formatNumber($balance['CapitalAccountBalance'],2);//可用余额
        $return['demandBalance']         = Helper::formatNumber($balance['demandBalance'],2);//e钱包金额
        if(false!==($data=Yii::app()->cache2->hgetall($user_id.'.Capital')))
        {
            // $return['settleAccountedAmount'] = Helper::formatNumber($data['settleAccountedAmount'],2);//已结算金额
            $return['recommendedAmount']     = Helper::formatNumber($data['RecommendedAmount'],2);//推荐获得奖励金额
            $return['recommendedCount']      = Helper::formatNumber($data['RecommendedCount'],2);//推荐用户数
            // $return['usedReward']            = Helper::formatNumber($data['UsedReward'],2);//使用过的红包
            $return['withdrawFrozen']        = Helper::formatNumber($data['WithdrawFrozen'],2);//冻结金额
            $return['rechargeTotal']         = Helper::formatNumber($data['RechargeTotal'],2);//充值总金额
            $return['totalRewardCash']       = Helper::formatNumber($data['TotalRewardCash'],2);//现金红包金额
            $return['investingAmount']       = Helper::formatNumber($data['investingAmount'],2);//投资中金额
            $return['investingCount']        = Helper::formatNumber($data['investingCount'],2);//投资中数量
            $return['totalRechargeCount']    = Helper::formatNumber($data['TotalRechargeCount'],2);//充值次数
            $return['totalInvestAmount']     = Helper::formatNumber($data['TotalInvestAmount'],2);//投资总额
            $return['finishedInvestTotal']   = Helper::formatNumber($data['FinishedInvestTotal'],2);//已结算金额
            $return['demandPayableInterest'] = Helper::formatNumber($data['demandPayableInterest'],2);//e钱包待收利息
            $return['demandHistory']         = Helper::formatNumber($data['demandHistory'],2);//e钱包历史收益
            $return['demandIncome']          = Helper::formatNumber($data['demandIncome'],2);//e钱包累计到账的活期宝利息
            $return['redeemDemandBalance']   = Helper::formatNumber($data['redeemDemandBalance'],2);//e钱包待赎回的本金
            $return['receivablePrincipal']   = Helper::formatNumber($data['ReceivablePrincipal'] + $balance['demandBalance'],2);//待收本金
            $return['receivedInterest']      = Helper::formatNumber($data['ReceivedInterest']+$data['demandIncome'],2);//已收利息
            $return['receivableInterest']    = Helper::formatNumber($data['ReceivableInterest'] + $data['demandPayableInterest'],2);//待收利息
            $coupon = json_decode($data['INDEX_COUPON_JSON']);
            $return['coupon']  = array(
                'annualTotalCount'   => $coupon->annualTotalCount,//年化券数量
                'annualUsableCount'  => $coupon->annualUsableCount,//可用年化券数量
                'couponAmount'       => $coupon->couponAmount,//投资券金额
                'couponCount'        => $coupon->couponCount,//投资券数量
                'couponUsableAmount' => $coupon->couponUsableAmount,//投资券可用金额
                'couponUsableCount'  => $coupon->couponUsableCount,//投资券可用数量
                'usedCouponAmount'   => $coupon->usedCouponAmount,//使用过的投资券金额
                'usedRewardAmount'   => $coupon->usedRewardAmount,//使用过的红包金额
            );
        }
        $userInitialized = true;//用户金额初始化
        $status = Yii::app()->cache2->hget('user.status',$user_id);
        if(in_array($status, array(1,3)))
            $userInitialized = false;
        if(!$userInitialized)
        {
            $return['rewardAccountBalance']         = Yii::app()->params['register_reward_bonus']['bonusAmount'];//注册送红包数量
            //$return['coupon']['couponUsableAmount'] = Yii::app()->params['register_reward_bonus']['couponAmount'];//注册送投资券金额
        }
        $return['accountTotal']    = number_format($balance['CapitalAccountBalance'] + $data['ReceivableInterest'] + $data['demandPayableInterest'] + $data['ReceivablePrincipal'] +
                                                    + $balance['demandBalance']+ $data['WithdrawFrozen'] + $balance['RewardAccountBalance']+$return['coupon']['couponUsableAmount']
                                                    + $data['redeemDemandBalance'],
                                                    2,'.','');
        $return['usedRewardTotal'] = number_format($return['coupon']['usedRewardAmount'] + $return['coupon']['usedCouponAmount']+$data['TotalRewardCash'],2,'.','');
        $return['totalInterest']   = number_format($data['ReceivedInterest'] + $data['demandIncome'] + $data['ReceivableInterest'] + $data['demandPayableInterest'] + $return['usedRewardTotal'],2,'.','');
        $return['eTotal']            = bcadd($balance['demandBalance'], $data['demandPayableInterest'],2);
        return $return;
    }
    /**
     * 获取用户余额
     */
    private function getBalance($user_id)
    {
        $keys    = Yii::app()->cache2->hkeys($user_id.'.Balance');
        $balance = Yii::app()->cache2->hgetall($user_id.'.Balance');
        if(count($keys)<2 || !$balance)
        {
            $remote = HttpLib::get($this->javaApi['user_balance'],array('user_id'=>$user_id));
            if($remote->success)
                $balance = (array)$remote->result;
            else
                $this->setResult(array(
                    'success' => 0,
                    'msg'     => $remote->errorMsg,
                ));
        }
        if(intval(date('H'))>16 && isset($balance['totalPayable']) && $balance['totalPayable']>0)
        {
            $remote = HttpLib::get('transaction/user/payable.json',array('user_id'=>$user_id));
            if(!$remote->success)
            {
                $this->setResult(array(
                    'success' => 0,
                    'msg'     => $remote->errorMsg,
                ));
            }
            $balance['CapitalAccountBalance'] = Helper::formatNumber($balance['CapitalAccountBalance'] + $balance['totalPayable']);
        }
        return $balance;
    }
    /**
     * 提现黑名单
     */
    public function  inWithdrawBlackList($user_id)
    {
        $allowed = Yii::app()->cache->hget($user_id.'.Capital','WithdrawAllowed');
        if($allowed && $allowed === 'no')
            return true;
        return false;
    }
    /**
     * 校验支付密码是否正确
     */
    public function checkPayPass($user_id,$payPass)
    {
        $params = array(
            'user_id' => $user_id,
            'password' => $payPass,
        );
        $remote = HttpLib::post($this->javaApi['pay_pass_verify'],$params);
        return $remote->success;
    }

    /**
     * 校验姓名和身份证
     */
    public function checkNameIdentity($user_id,$username,$identity)
    {
        $data = array(
            'success' => 0,
            'msg'     => '',
        );
        if(!$username || !$identity)
            $data['msg'] = '请填写姓名和身份证';
        elseif (!preg_match('/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/', $identity))
        {
            $data['msg']     = '请输入合法的身份证号';
            Yii::log('实名认证的身份证号码不合法,姓名是'.$username.',身份证号是'.$identity.'user_id='.$user_id,CLogger::LEVEL_WARNING,'api.warning.auth');
        }
        else
        {
            //默认身份证18位
            $birth = mb_substr($identity, 6,8);
            if(mb_strlen($identity)==15)
                $birth = '19'.mb_substr($identity, 6,6);
            $age = (int)(time()-strtotime($birth))/(3600*24*365);
            if(intval($age)<18)
                $data['msg'] = '您未满18周岁，认证不通过';
            else
            {
                //身份证是否已被绑定
                $exists = HttpLib::get($this->javaApi['user_check_identity_exists'],array('user_id'=>$user_id,'identity'=>$identity));
                $data['msg'] = $exists->errorMsg;
                if($exists!==null && !$exists->success)
                    $data['msg']     = '该身份证已被其他人绑定';
                else
                    $data['success'] = 1;
            }
        }
        return $data;
    }
    /**
     * 昨日收益
     */
    public function getYesterdayBenefit($user_id)
    {
        return Helper::formatNumber(Yii::app()->cache2->hget('demandYesterday',$user_id),2);
    }
    /**
     * 获取E钱包收益信息
     */
    public function getEwalletInfo($user_id)
    {
        $balance = $this->getBalance($user_id);
        $demandBalance      = Helper::formatNumber($balance['demandBalance'],2);//e钱包金额
        $pipe = Yii::app()->cache2->pipeline();
        $pipe->hget($user_id.'.Capital','demandPayableInterest');
        $pipe->hget($user_id.'.Capital','demandHistory');
        $pipe->hget('demandYesterday',$user_id);
        $pipe->hget('demandToday',$user_id);
        $dataList = $pipe->exec();
        foreach($dataList as $k=>$v)
            $dataList[$k] = Helper::formatNumber($v,2);
        $data = array(
            'interestYesterday'  => $dataList[2],
            'interestToady'      => $dataList[3],
            'interestTotal'      => $dataList[1],
            'eBalance'           => $demandBalance,
            'receivableInterest' => $dataList[0]>0?$dataList[0]:Helper::formatNumber(0,2),
        );
        $receivedInterest = $data['interestTotal'] - $data['receivableInterest'];
        $data['receivedInterest'] = Helper::formatNumber($receivedInterest,2);//已转出利息
        $data['eTotal'] = bcadd($demandBalance, $data['receivableInterest'],2);
        return $data;

    }
    /**
     * 获取e钱包购买记录
     */
    public function getEPurseList($user_id,$page=1,$limit=5)
    {
        $remote = HttpLib::post($this->javaApi['ewallet_purchase_list'],array(
            'user_id' => $user_id,
            'page'    => $page,
            'limit'   => $limit,
        ));
        if($remote->success && $remote->result)
        {
            $data = array();
            $data['totalCount'] = $remote->result->totalCount;
            $data['list'] = array();
            foreach($remote->result->pageList as $v)
            {
                $data['list'][] = array(
                    'id'            => $v->id,
                    'transactionId' => $v->transactionId,
                    'totalAmount'   => $v->totalAmount,//购买金额
                    'redeemAmount'  => $v->redeemAmount,//赎回金额
                    'surplusAmount' => $v->surplusAmount,//剩余金额
                    'createTime'    => date('Y-m-d H:i:s',$v->createTime/1000),
                    'updateTime'    => date('Y-m-d H:i:s',$v->updateTime/1000),
                );
            }
            return $data;
        }
        else
        {
            $this->setResult(array(
                'success' => 0,
                'msg'     => $remote->errorMsg,
            ));
        }
    }
    /**
     * 查询用户E钱包30天之内和30天之外的余额
     */
    public function getE30DayInfo($user_id)
    {
        $remote = HttpLib::post($this->javaApi['ewallet_query_info'],array('user_id'=> $user_id));
        if($remote->success && $remote->result)
            return  array(
                'inner' => $remote->result->inner,//不足30天金额
                'outer' => $remote->result->outer,//达到30天金额
            );
        else
            $this->setResult(array(
                'success' => 0,
                'msg'     => $remote->errorMsg,
            ));
    }
    /**
     * 获取用户当前积分
     */
    public function getScore($user_id)
    {
        $pipe = Yii::app()->cache2->pipeline();
        $pipe->hget($user_id.'.Capital','score'.date('Y'));
        $pipe->hget($user_id.'.Capital','score'.(date('Y')-1));
        return array_sum($pipe->exec());
    }

    /**
     * 初始化用户收益历史
     */
    private function initInterestHistory($userId)
    {
        $cache = Yii::app()->cache_new;
        if($cache->hget($userId.'.ListStateTag','InterestHistoryListTag'))
            return true;
        $remote = HttpLib::post('demand/init/interest/history.json',array('user_id'=>$userId));
        if($remote->success)
            return true;
        else
            $this->setResult(array(
                'success' => 0,
                'msg'     => $remote->errorMsg,
            ));
    }
    /**
     * 获取收益历史
     */
    public function getInterestHistory($userId,$page,$limit)
    {
        if($this->initInterestHistory($userId))
        {
            $cache = Yii::app()->cache_new;
            $k     = 'interestHistoryList.'.$userId;
            $count = $cache->llen($k);
            return array(
                'total'   => $count,
                'list'    => $cache->lrange($k,($page-1)*$limit,$page*$limit-1),
                'pageNum' => (int)(($count+$limit-1)/$limit),
                'max'     => Helper::formatNumber($cache->hget('MaxInterestInHistory',$userId),5,true),
                'min'     => Helper::formatNumber($cache->hget('MinInterestInHistory',$userId),5,true),
            );
        }
    }

    public function getBankcardList($user_id)
    {
        $cardList = array();
        $cache    = Yii::app()->cache2->hget($user_id.'.Capital','bankCardList');
        if($cache)
            $cards = json_decode($cache);
        else
        {
            $remote   = HttpLib::get('account/bankcard/list.json',array('user_id' => $user_id));
            if(!$remote->success)
                $this->setResult(array(
                    'success' => 0,
                    'msg'     => $remote->errorMsg,
                ));
            $cards = $remote->result;
        }
        if($cards)
        {
            $banks    = array();
            $bankList = Yii::app()->cache_php->lrange('llSupportedBanks',0,-1);
            if($bankList)
            {
                foreach($bankList as $b)
                {
                    $b = json_decode($b);
                    $banks[] = array(
                        'code'        => $b->code,
                        'name'        => $b->name,
                        'alias'       => $b->alias,
                        'needBranch'  => $b->needBranch,
                        'singleLimit' => $b->singleLimit,
                        'dayLimit'    => $b->dayLimit,
                        'monthLimit'  => $b->monthLimit,
                    );
                }
            }
            foreach($cards as $card)
            {
                $supportLL   = 0;//银行支持连连
                $needUpdate  = 0;//需要完善信息
                $needBranch  = 0;
                $singleLimit = $dayLimit = $monthLimit = 0;//支付限额
                if(in_array($card->bankId, Yii::app()->params['needBranchBankIds']))
                {
                    $needBranch = 1;
                    if(!$card->bankProvince || !$card->bankCity || !$card->subBranchName)
                        $needUpdate = 1;
                }
                foreach($banks as $bank)
                {
                    if($bank['code']==$card->bankId)
                    {
                        $supportLL   = 1;
                        $singleLimit = $bank['singleLimit'];
                        $dayLimit    = $bank['dayLimit'];
                        $monthLimit  = $bank['monthLimit'];
                        break;
                    }
                }
                $llMark  = ($card->status==0 && $supportLL )?1:0;//连连标识
                if(strpos($card->cardNumber, '*') === false)
                {
                    $card->fullCardNumber = $card->cardNumber;
                    $card->cardNumber     = str_repeat("*", strlen($card->cardNumber)-4).substr($card->cardNumber,-4,4);
                }
                $cardList[] = array(
                    'card_id'         => $card->id,
                    'cardNumber'      => $card->cardNumber,
                    'starCardNumber'  => mb_substr($card->fullCardNumber, 0,4).' **** **** '.mb_substr($card->fullCardNumber,-4),
                    'fullCardNumber'  => $card->fullCardNumber,
                    'last4number'     => substr($card->fullCardNumber,-4,4),//str_replace('*', '', $card->cardNumber),
                    'cardLast'        => substr($card->cardNumber,-4,4),
                    'cardHolder'      => $card->cardHolder,
                    'bankId'          => $card->bankId,
                    'bankProvince'    => $card->bankProvince?$card->bankProvince:'',
                    'bankCity'        => $card->bankCity?$card->bankCity:'',
                    'branchName'      => $card->subBranchName?$card->subBranchName:'',
                    'bankName'        => Yii::app()->params['bankcards'][$card->bankId],
                    'supportLL'       => $supportLL,
                    'llMark'          => $llMark,//连连标识
                    'needUpdate'      => $needUpdate,
                    'needRebind'      => $this->needReBind($card->bankId),
                    'payMethod'       => 3,//优先支付通道 3连连 5联动优势
                    'singleLimit'     => $singleLimit,
                    'dayLimit'        => $dayLimit,
                    'monthLimit'      => $monthLimit,
                    'availableAmount' => $card->availableAmount,
                    'protocolNo'      => $card->protocolNo?$card->protocolNo:'',
                );
            }
        }
        return $cardList;
    }
}
